<template>
  <div class="dashboard-container" id="home-app">
    <div class="container" style="padding: 0;background:rgb(243, 244, 247);">
      <div class="title-box">
        <div style="display: flex;justify-content: space-between;">
          <p>{{ userInfo }},{{ weathers.periodOfDay }}</p>
          <p>今天是{{ weathers.formattedDate }}</p>
        </div>
        <div class="weathers-box">{{ weathers.city }}&nbsp;&nbsp;&nbsp;&nbsp;
          <!-- <img :src="'@/assets/icons/'+ weathers.icon" :alt="weathers.weather " /> -->
          <img :src="weathers.icon ? require(`@/assets/icons/${weathers.icon}`) : ''" :alt="weathers.weather" />

          天气{{ weathers.weather }}&nbsp;&nbsp;&nbsp;&nbsp;<img src="@/assets/icons/cewen.png"
            :alt="weathers.temperature" />气温{{ weathers.temperature }}°
          &nbsp;&nbsp;&nbsp;&nbsp;<img src="@/assets/icons/fengxiang.png" :alt="weathers.weather" />
          {{ weathers.winddirection }}风向&nbsp;&nbsp;{{ weathers.windpower }}级
        </div>
      </div>
      <div class="common-layout">
        <el-container>
          <el-header style="height: auto">
            <div class="box-card">
              <el-card class="card">
                <template #header>
                  <div class="card-header">
                    <span style="font-size: 18px;color:#9e9e9e;">总销售额</span>
                  </div>
                </template>
                <div class="text item" style="font-size: 25px;font-weight: bold;">
                  <span style="font-size: 14px;">￥</span>
<count-to :startVal="0" :endVal="marketData.total_revenue" :decimals="2" :duration="3000"></count-to>
                </div>
              </el-card>
              <el-card class="card">
                <template #header>
                  <div class="card-header">
                    <span style="font-size: 18px;color:#9e9e9e;">月销售额</span>
                  </div>
                </template>
                <div class="text item" style="font-size: 25px;font-weight: bold;">
                  <span style="font-size: 14px;">￥</span>
                  <count-to :startVal="0" :endVal="marketData.current_month_revenue" :decimals="2" :duration="2000"></count-to>

                </div>
                <div class="footer" :class="{ 'goup': count, 'decline': !count }"><el-icon :style="marketData.month">
                    <ArrowUp v-if="count" />
                    <ArrowDown v-else />
                  </el-icon>&nbsp;&nbsp;<span>{{ marketData.month }}%</span></div>
              </el-card>
              <el-card class="card">
                <template #header>
                  <div class="card-header">
                    <span style="font-size: 18px;color:#9e9e9e;">总订单</span>
                  </div>
                </template>
                <div class="text item" style="font-size: 25px;font-weight: bold;">
                  <count-to :startVal="0" :endVal="marketData.order_quantity" :decimals="2" :duration="2000"></count-to>
                </div>
              </el-card><el-card class="card">
                <template #header>
                  <div class="card-header">
                    <span style="font-size: 18px;color:#9e9e9e;">本月订单</span>
                  </div>
                </template>
                <div class="text item" style="font-size: 25px;font-weight: bold;">
                  <count-to :startVal="0" :endVal="marketData.current_month_order_count" :decimals="2" :duration="2000"></count-to>
                </div>
                <div class="footer" :class="{ 'goup': revenue, 'decline': !revenue }"><el-icon>
                  <ArrowUp v-if="revenue" />
                    <ArrowDown v-else-if="!revenue" />
                  </el-icon>&nbsp;&nbsp;<span>{{ marketData.count }}%</span></div>
              </el-card>
            </div>
          </el-header>
          <el-container>
            <el-aside width="55%">
              <div class="left-card">
                <div class="title-card">
                  <div>热销菜品</div>
                  <router-link to="/dish"><div class="more">更多&nbsp;&nbsp;<el-icon><DishDot /></el-icon></div></router-link>
                </div>
                <div class="left-card-content">
                  <div class="content-card" v-for="item in tableData">
                    <el-image :src="item.image"  :preview-teleported="true">
                      <template #error>
                        <img src="@/assets/images/noImg.png" />
                      </template>
                    </el-image>
                    <div class="content-card-text">
                      <p>{{ item.name }}</p>
                      <p>
                        {{ item.description }}
                      </p>
                      <p>￥{{ item.price / 100 }}</p>
                    </div>
                  </div>
                </div>
              </div>
            </el-aside>
            <el-main style="padding-right: 0;padding-top: 0;">
              <div class="charts-list">
                <div class="charts-title">
                  <div>菜品销量</div>
                  <router-link to="/dish"><div class="more">更多&nbsp;&nbsp;<el-icon><Bowl /></el-icon></div></router-link>
                </div>
                <div style="margin-top: 30px;"></div>
                <div class="charts-bar" ref="myChart" id="myChart"></div>
              </div>
              <div class="charts-two">
                <div class="charts-left">
                  <div class="charts-title">
                    <div>收入排行</div>
                    <router-link to="/order"><div class="more">更多&nbsp;&nbsp;<el-icon><Food /></el-icon></div></router-link>
                </div>
                  <div class="charts-list-left" ref="ChartLeft" id="ChartLeft"></div>
                </div>
                <div style="width: 15px;"></div>
                <div class="charts-right">
                  <div class="charts-title">
                    <div>销量排行</div>
                    <router-link to="/order"><div class="more">更多&nbsp;&nbsp;<el-icon><IceTea /></el-icon></div></router-link>
                </div>
                  <div class="charts-list-right" ref="ChartRight" id="ChartRight"></div>
                </div>
              </div>
            </el-main>
          </el-container>
        </el-container>
      </div>
    </div>
  </div>
</template>
  
<script setup>
import { CountTo } from 'vue3-count-to';
import { getCurrentInstance, onMounted,onUnmounted } from "vue";
import { ref } from "vue";
import { getOrderMarket,getOrderTop } from "@/api/home/home";
import { getList } from "@/api/dish/dish";
import * as echarts from 'echarts'

const userInfo = window.sessionStorage.userName;
let weathers = ref({});
const marketData = ref({});
const topData =ref([]);
let count = ref(true);
let revenue = ref(true);
let formedData = [];
let dishName = [];
let totalAmount = [];
let totalQuantity = [];
const tableData = ref([]);
let myChart = ref();
let ChartRight = ref();
let ChartLeft = ref();
const listLFchart = () => {
   // 指定图表的配置项和数据
 const option = {
  xAxis: {
    type: 'category',
    data: dishName
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      data: totalAmount,
      type: 'line',
      smooth: true
    }
  ]
};
  const chart = echarts.init(ChartLeft.value)
  chart.setOption(option)
  window.addEventListener('resize', function(event) {
  // 处理滚轮事件的代码
  chart.resize()
}, { passive: true });
}
const listRTchart = () => {
   // 指定图表的配置项和数据
 const option = {
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: [
    {
      type: 'category',
      data: dishName,
      axisTick: {
        alignWithLabel: true
      }
    }
  ],
  yAxis: [
    {
      type: 'value'
    }
  ],
  series: [
    {
      name: '销量',
      type: 'bar',
      barWidth: '60%',
      data: totalQuantity
    }
  ]
};
  const chart = echarts.init(ChartRight.value)
  chart.setOption(option)
  window.addEventListener('resize', function(event) {
  // 处理滚轮事件的代码
  chart.resize()
}, { passive: true });
}
const drawLTchart = () => {
   // 指定图表的配置项和数据
 const option = {
  title: {
    text: '菜品销量分布饼图',
    subtext: '',
    left: 'center'
  },
  tooltip: {
    trigger: 'item'
  },
  legend: {
    orient: 'vertical',
    left: 'left'
  },
  series: [
    {
      name: '菜品',
      type: 'pie',
      radius: '50%',
      data: formedData,
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ]
};
  const chart = echarts.init(myChart.value)
  chart.setOption(option)
  window.addEventListener('resize', function(event) {
  // 处理滚轮事件的代码
  chart.resize()
}, { passive: true });
}

onMounted(() => {
    // 使用刚指定的配置项和数据显示图表。
    setTimeout(() => {
    drawLTchart()
    listRTchart()
    listLFchart()
  }, 1500)
})
onUnmounted(() => {
  // myChart.dispose()
})

//发起一个get请求查询后台的总销售额、销售订单等
const getOrderMarketlist = () => {
  getOrderMarket().then((res) => {
    if(res.code ==1){
      marketData.value = res.data || {};
      count.value = res.data.current_month_order_count - res.data.previous_month_order_count > 1 ? true : false;
      revenue.value = res.data.current_month_revenue - res.data.previous_month_revenue > 1 ? true : false;
      marketData.value.count = (marketData.value.previous_month_order_count / marketData.value.current_month_order_count).toFixed(2)* 100;
      marketData.value.month = (marketData.value.previous_month_revenue/marketData.value.current_month_revenue).toFixed(2)* 100;
    }
    });
    // 请求餐品销量排名和销售额排名
    getOrderTop().then((res) => {
    if(res.code ==1){
      topData.value = res.data
      formedData = res.data.map(item => ({
      value: item.totalQuantity,
      name: item.name
      }));
      dishName = res.data.map(item => (
        item.name
      )); 
      totalQuantity = res.data.map(item => (
      item.totalQuantity
    ));
    totalAmount = res.data.map(item => (
      item.totalAmount
    ));
    }
    });
};
const getDishList = () => {
  const params = {
    page: 1,
    pageSize: 4,
  };
  getList(params).then((res) => {
    tableData.value = res.data.records;
  });
};
const createdFunc = () => {
  getOrderMarketlist();
  getDishList();
};
createdFunc();



// 只需要填入key和你的城市信息，已经标记出来了
const axios = require("axios");
// 设置跨域请求头
axios.defaults.headers.post["Content-Type"] =
  "application/x-www-form-urlencoded";
// 定义post请求方法
const axiosPost = function (url, params) {
  return new Promise((resolve, reject) => {
    axios
      .post(url, params)
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  });
};
// 定义get请求方法
const axiosGet = function (url, params) {
  return new Promise((resolve, reject) => {
    axios
      .get(url, {
        params,
      })
      .then((res) => {
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  });
};
// 获取城市编码
async function getCity() {
  const params = {
    key: "1b5793161f6ecb18971a23fd5423580d", // 你的key  1
    address: "广东省东莞市", // 你的地址信息 2
  };
  let res = await axiosGet(
    "https://restapi.amap.com/v3/geocode/geo?parameters",
    params
  );
  return res.data.geocodes[0].adcode;
}
async function getWeather() {
  const adcode = await getCity();
  const params = {
    key: "1b5793161f6ecb18971a23fd5423580d", // 你的key  1
    city: adcode,
    extensions: "base",
  };
  let res = await axiosGet(
    "https://restapi.amap.com/v3/weather/weatherInfo?parameters",
    params
  );
  weathers.value = res.data.lives[0];
  const dateTimeString = weathers.value.reporttime;
  const timePart = dateTimeString.split(" ")[1]; // 提取时间部分
  const time = parseInt(timePart.split(":")[0]); // 提取小时部分并转换为整数
  // 解析日期字符串为日期对象
const dateObject = new Date(dateTimeString.split(" ")[0]);
// 提取年、月和日
const year = dateObject.getFullYear();
const month = dateObject.getMonth() + 1; // 月份是从0开始的，所以要加1
const day = dateObject.getDate();

// 格式化成 "2022年9月16日"
const formattedDate = `${year}年${month}月${day}日`;
let periodOfDay;
if (time >= 6 && time < 12) {
    periodOfDay = "早上好！新的一天，新的开始。";
} else if (time >= 12 && time < 18) {
    periodOfDay = "下午好！养好精神继续努力！";
} else {
    periodOfDay = "晚上好！请注意休息哦！";
}
//根据天气weather创建图标
const weatherIcons = {
  '晴': 'qing.png',
  '多云': 'icon_duoyun.png',
  '阴': 'icon_yintian.png',
  '阵雨': 'icon_zhenyu.png',
  '雷阵雨': 'icon_leizhenyu.png',
  '小雨': 'icon_xiaoyu.png',
  // 可以根据实际情况添加更多的天气状态和对应的图标
};
// 获取相应的图标
const icon = weatherIcons[weathers.value.weather] || 'icon_wushuju.png';
// const icon = weatherIcons[weather] || 'icon_wushuju.png';
weathers.value.icon = icon
weathers.value.formattedDate = formattedDate
weathers.value.periodOfDay = periodOfDay
}
getWeather();
</script>

<style lang="scss" scoped>
a{
  text-decoration: none;
}
.more{
  display: flex;
  align-items: center; /* 垂直居中 */
  justify-content: space-between;
  line-height: 30px;
  font-size: 18px;
  color: #999;
  
}
.el-header {
  padding: 0 !important;
}

.goup {
  /* 样式规则 */
  color: green;
  font-weight: bolder;
}

.decline {
  /* 样式规则 */
  color: red;
}

.el-image {
  vertical-align: middle;
  border-radius: 10px;
  height: 120px;
  min-width: 200px;
}

.title-box {
  height: 70px;
  background-color: white;
  box-shadow: rgba(149, 157, 165, 0.2) 0px 8px 24px;
  border-radius: 10px;
  padding: 15px;
  margin-bottom: 20px;

  .weathers-box {
    display: flex;
    align-items: center;
    margin-top: 10px;
    font-size: 18px;
  }

  p {
    margin: 5px 0;
    font-size: 18px;
  }

  img {
    height: 30px;
  }
}

.box-card {
  display: flex;
  justify-content: flex-start;
  width: 100%;
  margin-bottom: 20px;
  height: 150px;

  .card {
    width: 25%;
    height: 150px;
    margin-right: 20px;
    border-radius: 10px;

    .footer {
      margin-top: 10px;
      font-size: 16px;
    }
  }

  .card:last-child {
    margin-right: 0;
  }
}

.title-card {
  height: 30px;
  display: flex;
  align-items: center; /* 垂直居中 */
  justify-content: space-between;
  padding: 10px 0;
  margin-bottom: 5px;
  font-size: 18px;
}

.left-card {
  padding: 0 20px;
  border-radius: 10px;
  background-color: white;
  min-height: 640px;

  .left-card-content {
    .content-card {
      display: flex;
      align-items: flex-start;
      margin-bottom: 15px;

      img {
        height: 120px;
        width: auto;
      }

      .content-card-text {
        font-size: 14px;
        margin-top: 10px;
        margin-left: 10px;

        p:first-child {
          font-size: 16px;
          font-weight: bolder;
        }

        p {
          margin-top: 0;
        }

        p:nth-child(2) {
          min-height: 40px;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }
      }
    }
  }
}

.charts-list {
  box-shadow: rgba(149, 157, 165, 0.2) 0px 8px 24px;
  background-color: white;
  padding: 15px;
  border-radius: 10px;

  .charts-bar {
    margin-top: 10px;
    width:540px;
    height:240px;
  }
}

.charts-two {
  width: 100%;
  display: flex;
  align-content: flex-start;
  margin-top: 20px;

  .charts-right {
    padding: 15px;
    box-shadow: rgba(149, 157, 165, 0.2) 0px 8px 24px;
    background-color: white;
    padding: 15px;
    height: 265px;
    width: 50%;
    border-radius: 10px;
  }

  .charts-left {
    padding: 15px;
    width: 50%;
    height: 265px;
    box-shadow: rgba(149, 157, 165, 0.2) 0px 8px 24px;
    background-color: white;
    border-radius: 10px;
  }

 .charts-list-right{

    width: 100%;
    height: 90%;
  }
  .charts-list-left{
    width: 100%;
    height: 100%;
    
  }
}

.charts-title {
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 5px;
  font-size: 18px;
}
</style>